<!-- CourseStudy.vue -->
<template>
  <!-- 课程学习页面容器 -->
  <div class="course-study-container">
    <!-- 顶部导航栏 -->
    <div class="course-study-header">
      <div class="back-nav">
        <div class="back-button" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回</span>
        </div>
      </div>
      <h1 class="course-title">{{ courseData.title || '课程学习' }}</h1>
    </div>

    <!-- 主要内容区域 -->
    <div class="course-study-content" v-loading="loading">
      <template v-if="!loading && courseData">
        <!-- 课程信息面板 -->
        <div class="course-info-panel">
          <!-- 课程时间信息 -->
          <div class="schedule-info">
            <h3>课程信息</h3>
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>上课日期：{{ courseData.date || '未设置' }}</span>
            </div>
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span>上课时间：{{ courseData.startTime || '未设置' }} - {{ courseData.endTime || '未设置' }}</span>
            </div>
            <div class="course-actions">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleRefund"
                :loading="refunding"
              >
                申请退款
              </el-button>
            </div>
          </div>

          <!-- 教师信息展示区域 -->
          <div class="teacher-profile-section" v-if="courseData.teacherName">
            <h3>教师信息</h3>
            <div class="teacher-profile">
              <el-avatar 
                :size="64" 
                :src="courseData.teacherAvatar"
                class="teacher-avatar"
              />
              <div class="teacher-details">
                <div class="teacher-name">{{ courseData.teacherName }}</div>
                <div class="teacher-title">{{ courseData.teacherTitle }}</div>
              </div>
            </div>
            <div class="teacher-additional-info">
              <div class="info-row">
                <span class="info-label">学历：</span>
                <span class="info-value">{{ courseData.teacherEducation }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">学校：</span>
                <span class="info-value">{{ courseData.teacherSchool }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">教学风格：</span>
                <span class="info-value">{{ courseData.teacherTeachingStyle }}</span>
              </div>
              <div class="info-row teacher-introduction">
                <span class="info-label">个人简介：</span>
                <span class="info-value">{{ courseData.teacherIntroduction }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 课程主要内容区域 -->
        <div class="course-main-content">
          <el-tabs v-model="activeTab" class="course-tabs">
            <!-- 课程内容标签页 -->
            <el-tab-pane label="课程内容" name="content">
              <div class="content-section">
                <template v-if="courseData.content">
                  <!-- 课程标题图片 -->
                  <div class="title-image" v-if="courseData.titleImg">
                    <img :src="courseData.titleImg" alt="课程标题图片" style="width:100%;border-radius:8px;margin-bottom:20px;">
                  </div>
                  
                  <!-- 课程详情内容 -->
                  <div class="course-details">
                    <div class="content-text markdown-content" v-html="renderMarkdown(courseData.content)"></div>
                  </div>
                  
                  <!-- 课程内容图片展示 -->
                  <div class="content-images">
                    <img v-if="courseData.content1Img" 
                         :src="courseData.content1Img" 
                         alt="课程内容图片1" 
                         class="content-image">
                    <img v-if="courseData.content2Img" 
                         :src="courseData.content2Img" 
                         alt="课程内容图片2" 
                         class="content-image">
                    <img v-if="courseData.content3Img" 
                         :src="courseData.content3Img" 
                         alt="课程内容图片3" 
                         class="content-image">
                    <img v-if="courseData.content4Img" 
                         :src="courseData.content4Img" 
                         alt="课程内容图片4" 
                         class="content-image">
                  </div>
                </template>
                <template v-else>
                  <el-empty description="课程内容准备中..." />
                </template>
              </div>
            </el-tab-pane>

            <!-- 课程资料标签页 -->
            <el-tab-pane label="课程资料" name="materials">
              <div class="materials-section">
                <template v-if="courseData.materials && courseData.materials.length > 0">
                  <div class="material-list">
                    <div v-for="material in courseData.materials" 
                         :key="material.id" 
                         class="material-item">
                      <el-icon><Document /></el-icon>
                      <span class="material-name">{{ material.name }}</span>
                      <el-button 
                        type="primary" 
                        link 
                        @click="downloadMaterial(material)"
                      >
                        下载
                      </el-button>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <el-empty description="暂无课程资料" />
                </template>
              </div>
            </el-tab-pane>

            <!-- 课后讨论标签页 -->
            <el-tab-pane label="课后讨论" name="discussion">
              <div class="discussion-section">
                <!-- 评论输入区域 -->
                <div class="comment-input-section">
                  <h3 class="section-title">发表评价</h3>
                  <div class="rating-container">
                    <span class="rating-label">评分：</span>
                    <el-rate 
                      v-model="reviewForm.rating" 
                      :texts="['1分','2分','3分','4分','5分']"
                      show-text
                    />
                  </div>
                  <el-input
                    v-model="reviewForm.content"
                    type="textarea"
                    :rows="4"
                    placeholder="分享你对这门课程的感受和建议..."
                    resize="none"
                    class="comment-textarea"
                  />
                  <div class="comment-actions">
                    <el-button type="primary" @click="submitReview" :loading="submitting">
                      <el-icon class="el-icon--left"><Edit /></el-icon>
                      发表评价
                    </el-button>
                  </div>
                </div>

                <!-- 课程评价区域 -->
                <div class="review-section">
                  <h3 class="section-title">课程评价</h3>
                  
                  <!-- 评论列表 -->
                  <div class="review-list">
                    <!-- 处理主评论及其回复 -->
                    <template v-for="review in getFormattedReviews()" :key="review.reviewId">
                      <!-- 主评论 -->
                      <div class="review-item">
                        <div class="main-review" 
                             @click="loadReviewReplies(review.courseReview.reviewId)" 
                             :class="{'clickable': !review.repliesLoaded}">
                          <div class="user-info">
                            <el-avatar :size="40" :src="review.userImg" />
                            <div class="user-detail">
                              <span class="user-name">{{ review.userName }}</span>
                              <el-rate v-model="review.courseReview.rating" disabled />
                        </div>
                      </div>
                          <div class="review-content">{{ review.courseReview.content }}</div>
                          <div class="review-time">
                            {{ formatDate(review.courseReview.createdTime) }}
                            <span v-if="!review.repliesLoaded" class="click-hint">
                              <el-icon><ArrowDown /></el-icon> 点击查看回复
                            </span>
                          </div>
                      </div>
                      
                        <!-- 教师回复 -->
                        <div v-if="review.courseReview.teacherReply" class="teacher-reply">
                          <div class="review-teacher-info">
                            <el-avatar :size="40" :src="review.teacherImg" />
                            <span class="teacher-name">{{ review.teacherName }}</span>
                          </div>
                          <div class="reply-content">{{ review.courseReview.teacherReply }}</div>
                          <div class="reply-time">{{ formatDate(review.courseReview.updatedTime) }}</div>
                        </div>
                        
                        <!-- 子评论(回复) -->
                        <div v-if="review.replies && review.replies.length > 0" class="reply-list">
                          <div v-for="reply in review.replies" :key="reply.courseReview.reviewId" class="reply-item">
                          <div class="reply-header">
                              <el-avatar :size="32" :src="reply.userImg" />
                            <div class="reply-info">
                              <div class="reply-user">{{ reply.userName }}</div>
                                <el-rate v-model="reply.courseReview.rating" disabled size="small" />
                            </div>
                          </div>
                            <div class="reply-content">{{ reply.courseReview.content }}</div>
                            <div class="reply-time">{{ formatDate(reply.courseReview.createdTime) }}</div>
                          </div>
                        </div>

                        <!-- 回复按钮 -->
                        <div class="review-actions">
                          <el-button 
                            type="primary" 
                            link 
                            size="small" 
                            @click.stop="openReplyForm(review.courseReview.reviewId, $event)"
                          >
                            <el-icon><ChatLineRound /></el-icon> 回复
                          </el-button>
                          <el-button 
                            v-if="userIdMatch[review.courseReview.studentId]"
                            type="danger" 
                            link 
                            size="small" 
                            @click.stop="confirmDeleteReview(review.courseReview.reviewId, $event)"
                          >
                            <el-icon><Delete /></el-icon> 删除
                          </el-button>
                        </div>

                        <!-- 回复表单 -->
                        <div v-if="showReplyForm && replyToReviewId === review.courseReview.reviewId" class="reply-form">
                          <el-input
                            v-model="replyForm.content"
                            type="textarea"
                            :rows="3"
                            placeholder="添加回复..."
                            resize="none"
                          />
                          <div class="rating-container">
                            <span class="rating-label">评分：</span>
                            <el-rate v-model="replyForm.rating" />
                          </div>
                          <div class="reply-form-actions">
                            <el-button size="small" @click.stop="cancelReply">取消</el-button>
                            <el-button 
                              type="primary" 
                              size="small" 
                              @click.stop="submitReply(review.courseReview.reviewId)"
                              :loading="submittingReply"
                            >
                              发表回复
                            </el-button>
                        </div>
                      </div>
                    </div>
                  </template>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <!-- 错误提示区域 -->
      <el-result
        v-if="error"
        icon="error"
        :title="error"
        sub-title="请稍后重试"
      >
        <template #extra>
          <el-button type="primary" @click="fetchCourseData">重试</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Calendar, Timer, Document, Edit, ArrowDown, ChatLineRound, Delete } from '@element-plus/icons-vue'
import { getCourseStudyInfo, getTeacherInfo, getCourseReviewList, getCourseReviewReplyList, insertCourseReview, replyCourseReview, deleteCourseReview, selectBookingByScheduleIdAndCourseId } from '@/api/course'
import { verifyToken } from '@/api/user'
import { refund } from '@/api/order'
import { marked } from 'marked'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const error = ref('')
const courseData = ref({})
const activeTab = ref('content')
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const courseId = ref(null)
const reviewList = ref([])
const showReplyForm = ref(false)
const replyToReviewId = ref(null)

// 评论相关的响应式数据
const reviewForm = ref({
  rating: 5,
  content: '',
  bookingId: null,
  teacherId: null,
  studentId: null,
  parentId: null,
  courseId: null
})

// 回复表单数据
const replyForm = ref({
  content: '',
  rating: 5,
  parentId: null,
  bookingId: null,
  teacherId: null,
  courseId: null,
  studentId: null
})

const submitting = ref(false)
const submittingReply = ref(false)
const userIdMatch = ref({})
const verifying = ref(false)
const refunding = ref(false)

/**
 * 获取教师信息
 * @param {string|number} courseId - 课程ID
 * @returns {Object} 教师信息对象
 */
const fetchTeacherInfo = async (courseId) => {
  try {
    const response = await getTeacherInfo(courseId)
    if (response.code === 200) {
      const teacherInfo = response.data

      // 获取头像URL
      const headImage = teacherInfo.ossImages?.find(img => img.relationType === 'head')
      const avatarUrl = headImage?.url || defaultAvatar

      return {
        teacherName: teacherInfo.userName || '教师',
        teacherTitle: '教师',
        teacherAvatar: avatarUrl,
        teacherEducation: teacherInfo.education || '未提供',
        teacherSchool: teacherInfo.school || '未提供',
        teacherTeachingStyle: teacherInfo.teacher?.teachingStyle || '未提供',
        teacherIntroduction: teacherInfo.teacher?.introduction || '未提供'
      }
    } else {
      return getDefaultTeacherInfo()
    }
  } catch (err) {
    return getDefaultTeacherInfo()
  }
}

/**
 * 获取默认教师信息
 * @returns {Object} 默认教师信息对象
 */
const getDefaultTeacherInfo = () => ({
  teacherName: '教师',
  teacherTitle: '教师',
  teacherAvatar: defaultAvatar,
  teacherEducation: '未提供',
  teacherSchool: '未提供',
  teacherTeachingStyle: '未提供',
  teacherIntroduction: '未提供'
})

/**
 * 获取课程学习数据
 */
const fetchCourseData = async () => {
  const scheduleId = route.params.scheduleId
  if (!scheduleId) {
    error.value = '无效的课程安排ID'
    loading.value = false
    return
  }

  loading.value = true
  error.value = ''

  try {
    const response = await getCourseStudyInfo(scheduleId)
    if (response.code === 200) {
      const courseInfo = response.data
      
      // 从响应中获取courseId
      courseId.value = courseInfo.courseId
      
      // 设置评论表单的课程相关数据
      reviewForm.value.courseId = courseInfo.courseId
      reviewForm.value.teacherId = courseInfo.teacherId || 110002
      reviewForm.value.bookingId = courseInfo.bookingId || 190367
      reviewForm.value.studentId = 110001
      
      // 提取课程安排信息
      const schedule = courseInfo.teacherSchedule && courseInfo.teacherSchedule.length > 0 
        ? courseInfo.teacherSchedule[0] 
        : null
      
      // 获取教师信息
      const teacherInfo = await fetchTeacherInfo(courseInfo.courseId)
      
      // 构建课程数据对象
      courseData.value = {
        title: courseInfo.title,
        content: courseInfo.details,
        titleImg: courseInfo.titleImg,
        content1Img: courseInfo.content1Img,
        content2Img: courseInfo.content2Img,
        content3Img: courseInfo.content3Img,
        content4Img: courseInfo.content4Img,
        date: schedule ? schedule.date : '未设置',
        startTime: schedule ? schedule.startTime : '未设置',
        endTime: schedule ? schedule.endTime : '未设置',
        teacherName: teacherInfo.teacherName,
        teacherTitle: teacherInfo.teacherTitle,
        teacherAvatar: teacherInfo.teacherAvatar,
        teacherEducation: teacherInfo.teacherEducation,
        teacherSchool: teacherInfo.teacherSchool,
        teacherTeachingStyle: teacherInfo.teacherTeachingStyle,
        teacherIntroduction: teacherInfo.teacherIntroduction,
        materials: []
      }
    } else {
      error.value = response.message || '获取课程信息失败'
    }
  } catch (err) {
    error.value = '获取课程信息失败'
  } finally {
    loading.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

/**
 * 下载课程资料
 * @param {Object} material - 资料对象
 */
const downloadMaterial = (material) => {
  ElMessage.success('开始下载：' + material.name)
}

/**
 * 获取评论列表
 */
const fetchComments = async () => {
  try {
    // 已不再使用的函数，保留函数签名以避免潜在的引用错误
  } catch (error) {
    ElMessage.error('获取评论失败')
  }
}

/**
 * 提交评论
 */
const submitReview = async () => {
  if (!reviewForm.value.content.trim()) {
    ElMessage.warning('请输入评价内容')
    return
  }

  if (!reviewForm.value.courseId) {
    ElMessage.warning('课程信息不完整，无法提交评价')
    return
  }

  submitting.value = true
  try {
    const response = await insertCourseReview(reviewForm.value)
    
    if (response.code === 200) {
      ElMessage.success('评价发表成功')
      
      // 清空评价内容，保留评分
      reviewForm.value.content = ''
      
      // 刷新评价列表
      fetchReviewList()
    } else {
      ElMessage.error('评价发表失败：' + response.message)
    }
  } catch (error) {
    ElMessage.error('评价发表失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 获取评论列表
const fetchReviewList = async () => {
  try {
    if (!courseId.value) {
      ElMessage.warning('课程ID不能为空')
      return
    }
    
    const response = await getCourseReviewList(courseId.value)
    
    if (response.code === 200) {
      reviewList.value = response.data
      
      // 列出所有评论的用户ID，准备验证
      const userIds = reviewList.value
        .map(review => review.courseReview.studentId)
        .filter(id => id)
      
      // 验证用户身份
      verifyUserIds(userIds)
      
      // 获取评论列表成功后，获取预约信息
      const scheduleId = route.params.scheduleId
      if (scheduleId && courseId.value) {
        try {
          const bookingResponse = await selectBookingByScheduleIdAndCourseId(scheduleId, courseId.value)
          if (bookingResponse.code === 200 && bookingResponse.data) {
            // 将bookingId赋值给reviewForm
            reviewForm.value.bookingId = bookingResponse.data.bookingId || 190367
          } else {
            console.error('获取预约信息失败:', bookingResponse.message)
          }
        } catch (error) {
          console.error('获取预约信息出错:', error)
        }
      }
    } else {
      ElMessage.error('获取评论列表失败：' + response.message)
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败：' + (error.message || '未知错误'))
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

/**
 * 处理评论数据，组织成主评论和回复的层次结构
 */
const getFormattedReviews = () => {
  // 克隆评论列表防止修改原始数据
  const reviews = JSON.parse(JSON.stringify(reviewList.value))
  
  // 主评论Map，用于存储主评论
  const mainReviews = {}
  
  // 处理回复关系
  reviews.forEach(review => {
    // 如果是主评论
    if (review.courseReview.parentId === 0) {
      // 保留已经加载好的replies
      const existingReplies = review.replies || []
      review.replies = existingReplies
      mainReviews[review.courseReview.reviewId] = review
    } else {
      // 如果是回复
      const parentId = review.courseReview.parentId
      if (mainReviews[parentId]) {
        // 如果主评论Map中已存在此父评论
        if (!mainReviews[parentId].replies) {
          mainReviews[parentId].replies = []
        }
        
        // 避免重复添加
        const alreadyExists = mainReviews[parentId].replies.some(
          r => r.courseReview.reviewId === review.courseReview.reviewId
        )
        
        if (!alreadyExists) {
          mainReviews[parentId].replies.push(review)
        }
      }
    }
  })
  
  // 返回主评论列表
  return Object.values(mainReviews)
}

/**
 * 加载评论的回复列表
 * @param {number} reviewId - 评论ID
 */
const loadReviewReplies = async (reviewId) => {
  try {
    if (!reviewId) {
      ElMessage.warning('评论ID不能为空')
    return
  }

    const response = await getCourseReviewReplyList(reviewId)
    
    if (response.code === 200) {
      // 标记所有评论为未加载状态
      const updatedReviewList = JSON.parse(JSON.stringify(reviewList.value))
      
      // 找到当前评论并标记为已加载
      const updatedList = updatedReviewList.map(review => {
        // 如果是目标评论，标记为已加载并添加回复
        if (review.courseReview.reviewId === reviewId) {
          return {
            ...review,
            repliesLoaded: true,
            // 保存原有回复，防止重复加载
            replies: response.data
          }
        }
        return review
      })
      
      // 更新响应式数据
      reviewList.value = updatedList
      
    } else {
      ElMessage.error('获取评论回复失败：' + response.message)
    }
  } catch (error) {
    ElMessage.error('获取评论回复失败：' + (error.message || '未知错误'))
  }
}

/**
 * 打开回复表单
 * @param {number} reviewId - 要回复的评论ID
 */
const openReplyForm = (reviewId, e) => {
  // 停止事件传播，防止触发点击评论加载回复的事件
  e.stopPropagation()
  
  // 设置当前回复的评论ID
  replyToReviewId.value = reviewId
  showReplyForm.value = true
  
  // 重置回复表单内容，但保留课程信息
  replyForm.value = {
    parentId: reviewId,
    content: '',
    rating: 5,
    bookingId: reviewForm.value.bookingId,
    teacherId: reviewForm.value.teacherId,
    courseId: reviewForm.value.courseId,
    studentId: reviewForm.value.studentId
  }
}

/**
 * 取消回复
 */
const cancelReply = () => {
  showReplyForm.value = false
  replyToReviewId.value = null
  replyForm.value.content = ''
}

/**
 * 提交回复
 * @param {number} reviewId - 被回复的评论ID
 */
const submitReply = async (reviewId) => {
  if (!replyForm.value.content.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  submittingReply.value = true
  try {
    // 设置父评论ID
    replyForm.value.parentId = reviewId
    
    const response = await replyCourseReview(replyForm.value)
    
    if (response.code === 200) {
      ElMessage.success('回复发表成功')
      
      // 关闭回复表单
      cancelReply()
      
      // 重新加载该评论的回复列表
      loadReviewReplies(reviewId)
    } else {
      ElMessage.error('回复发表失败：' + response.message)
    }
  } catch (error) {
    ElMessage.error('回复发表失败：' + (error.message || '未知错误'))
  } finally {
    submittingReply.value = false
  }
}

/**
 * 验证用户身份
 * @param {number[]} userIds - 用户ID数组
 */
const verifyUserIds = async (userIds) => {
  if (!userIds || userIds.length === 0) return
  
  // 过滤出未验证过的用户ID
  const unverifiedIds = userIds.filter(id => userIdMatch.value[id] === undefined)
  if (unverifiedIds.length === 0) return
  
  verifying.value = true
  
  try {
    // 验证每个用户ID，采用Promise.all但捕获所有错误
    const verifyPromises = unverifiedIds.map(userId => {
      return verifyToken(userId)
        .then(response => {
          if (response && response.code === 200) {
            userIdMatch.value[userId] = !!response.data
          } else {
            userIdMatch.value[userId] = false
          }
        })
        .catch(() => {
          // 静默处理单个请求错误
          userIdMatch.value[userId] = false
        });
    });
    
    // 等待所有验证完成，但不抛出错误
    await Promise.allSettled(verifyPromises);
  } catch (error) {
    // 静默处理整体错误
    console.error('验证用户身份过程中发生错误:', error);
  } finally {
    verifying.value = false
  }
}

/**
 * 确认删除评论
 * @param {number} reviewId - 评论ID
 * @param {Event} e - 事件对象
 */
const confirmDeleteReview = (reviewId, e) => {
  e.stopPropagation()
  
  ElMessageBox.confirm(
    '确定要删除这条评论吗？',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用删除API
    deleteReview(reviewId)
  }).catch(() => {
    // 用户取消删除操作
  })
}

/**
 * 执行删除评论
 * @param {number} reviewId - 评论ID
 */
const deleteReview = async (reviewId) => {
  try {
    const response = await deleteCourseReview(reviewId)
    
    if (response.code === 200) {
      ElMessage.success('评论删除成功')
      
      // 从列表中移除该评论
      removeReviewFromList(reviewId)
    } else {
      ElMessage.error('删除评论失败：' + response.message)
    }
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败：' + (error.message || '未知错误'))
  }
}

/**
 * 从评论列表中移除指定评论
 * @param {number} reviewId - 评论ID
 */
const removeReviewFromList = (reviewId) => {
  // 过滤出主评论
  const isMainReview = reviewList.value.some(review => 
    review.courseReview.reviewId === reviewId && review.courseReview.parentId === 0
  )
  
  if (isMainReview) {
    // 如果是主评论，则连同其回复一起删除
    reviewList.value = reviewList.value.filter(review => 
      review.courseReview.reviewId !== reviewId && review.courseReview.parentId !== reviewId
    )
  } else {
    // 如果是回复评论，只删除该评论
    reviewList.value = reviewList.value.filter(review => 
      review.courseReview.reviewId !== reviewId
    )
  }
}

/**
 * 处理退款请求
 */
const handleRefund = async () => {
  // 确认对话框
  try {
    await ElMessageBox.confirm(
      '确定要申请退款吗？一旦退款将无法恢复预约。', 
      '退款确认', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 用户确认后处理退款
    refunding.value = true
    const scheduleId = route.params.scheduleId
    
    try {
      const response = await refund(scheduleId)
      if (response.code === 200) {
        // 显示退款说明
        ElMessage.success('退款通过后，将会在5个工作日内返回您的账户')
        router.push('/')
        
      } else {
        ElMessage.error(response.message || '退款申请失败')
      }
    } catch (error) {
      console.error('退款请求失败:', error)
      ElMessage.error('退款申请失败: ' + (error.message || '未知错误'))
    } finally {
      refunding.value = false
    }
  } catch (e) {
    // 用户取消，不做任何操作
  }
}

// 渲染Markdown内容
const renderMarkdown = (content) => {
  if (!content) return '';
  try {
    return marked(content);
  } catch (error) {
    console.error('Markdown渲染错误:', error);
    return content;
  }
};

onMounted(() => {
  console.log('组件挂载，当前路由参数:', route.query)
  console.log('当前路径:', route.path)
  
  fetchCourseData() // 先获取课程数据，其中会包含courseId
  fetchComments()
  // 不在这里调用fetchReviewList，改为在fetchCourseData成功后调用
})

// 添加对activeTab的监听，当切换到discussion标签时加载评论
watch(activeTab, (newVal) => {
  if (newVal === 'discussion') {
    // 检查评论列表是否已经加载
    if (reviewList.value.length === 0 && courseId.value) {
      // 加载评论列表
      fetchReviewList().catch(() => {
        ElMessage.error('获取评论列表失败')
      });
      
      // 如果已有评论数据，进行身份验证
      if (reviewList.value.length > 0) {
        const userIds = reviewList.value
          .map(review => review.courseReview.studentId)
          .filter(id => id);
        
        // 处理身份验证
        setTimeout(() => {
          verifyUserIds(userIds).catch(() => {
            ElMessage.error('验证用户身份失败')
          });
        }, 500);
      }
    }
  }
})
</script>

<style scoped>
.course-study-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.course-study-header {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-nav {
  display: flex;
  align-items: center;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #f5f7fa;
}

.course-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.course-study-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
  min-height: calc(100vh - 200px);
}

.course-info-panel {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.schedule-info h3,
.teacher-profile-section h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #606266;
}

.course-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.teacher-profile-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.teacher-profile {
  display: flex;
  align-items: center;
  gap: 16px;
}

.teacher-details {
  flex: 1;
}

.teacher-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.teacher-title {
  font-size: 14px;
  color: #909399;
}

.course-main-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.content-section,
.materials-section {
  padding: 16px 0;
}

.content-section {
  padding: 20px;
}

.title-image img {
  width: 100%;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-details {
  margin: 20px 0;
  line-height: 1.8;
  color: #303133;
}

.content-text {
  font-size: 15px;
  white-space: pre-line;
}

.content-images {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.content-image {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.material-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.material-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.material-name {
  flex: 1;
  color: #303133;
}

.teacher-additional-info {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #ebeef5;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.5;
}

.info-label {
  color: #909399;
  width: 80px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  flex: 1;
}

.teacher-introduction {
  flex-direction: column;
  align-items: flex-start;
}

.teacher-introduction .info-value {
  margin-top: 4px;
  white-space: pre-line;
}

@media (max-width: 768px) {
  .course-study-content {
    grid-template-columns: 1fr;
  }
}

.discussion-section {
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.comment-input-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.comment-textarea {
  margin-bottom: 16px;
}

.comment-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.comment-textarea :deep(.el-textarea__inner:focus) {
  background-color: #fff;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.comment-list-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.comment-item {
  padding: 20px;
  border-radius: 8px;
  background-color: #f5f7fa;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.comment-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.comment-info {
  flex: 1;
}

.comment-user {
  font-weight: 500;
  color: #303133;
  font-size: 15px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.comment-content {
  color: #303133;
  line-height: 1.8;
  font-size: 14px;
  padding: 0 4px;
}

.comment-footer {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.reply-button {
  font-size: 13px;
  padding: 4px 8px;
}

.reply-list {
  margin-top: 16px;
  margin-left: 48px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reply-item {
  padding: 16px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.reply-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.reply-info {
  flex: 1;
}

.reply-user {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.reply-time {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.reply-content {
  color: #303133;
  font-size: 14px;
  line-height: 1.6;
  padding: 0 4px;
}

@media (max-width: 768px) {
  .discussion-section {
    padding: 16px;
  }
  
  .reply-list {
    margin-left: 24px;
  }
}

.review-section {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.main-review {
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.review-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.review-time {
  font-size: 12px;
  color: #909399;
}

.teacher-reply {
  margin-left: 40px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.review-teacher-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.teacher-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.reply-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}

.main-review.clickable {
  cursor: pointer;
  transition: all 0.3s ease;
}

.main-review.clickable:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.click-hint {
  margin-left: 8px;
  font-size: 12px;
  color: #409eff;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.rating-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.rating-label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.review-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.reply-form {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.reply-form-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* Markdown内容样式 */
.markdown-content {
  line-height: 1.6;
  color: #333;
}

.markdown-content :deep(h1) {
  font-size: 1.8em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(h2) {
  font-size: 1.5em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(h3) {
  font-size: 1.3em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-content :deep(p) {
  margin-bottom: 1em;
}

.markdown-content :deep(ul), .markdown-content :deep(ol) {
  margin-bottom: 1em;
  padding-left: 2em;
}

.markdown-content :deep(li) {
  margin-bottom: 0.5em;
}

.markdown-content :deep(code) {
  background-color: #f5f5f5;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-content :deep(pre) {
  background-color: #f5f5f5;
  padding: 1em;
  border-radius: 5px;
  overflow-x: auto;
  margin-bottom: 1em;
}

.markdown-content :deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 1em;
  margin-left: 0;
  color: #666;
}

.markdown-content :deep(a) {
  color: #1890ff;
  text-decoration: none;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}

.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 5px;
  margin: 1em 0;
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 1em;
}

.markdown-content :deep(th), .markdown-content :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.markdown-content :deep(th) {
  background-color: #f5f5f5;
}
</style> 